package com.ishow.noah.modules.androidx.camerax

import android.os.Bundle
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.google.common.util.concurrent.ListenableFuture
import com.ishow.noah.R
import com.ishow.noah.databinding.FSamlpeCameraxBinding
import com.ishow.noah.modules.base.mvvm.view.AppBindFragment
import kotlinx.android.synthetic.main.f_samlpe_camerax.*
import java.util.concurrent.Executor

/**
 * Created by yuhaiyang on 2020-02-02.
 */
class SampleCameraXFragment : AppBindFragment<FSamlpeCameraxBinding, SampleCameraXViewModel>() {

    private lateinit var mainExecutor: Executor

    override fun getLayout(): Int = R.layout.f_samlpe_camerax

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainExecutor = ContextCompat.getMainExecutor(requireContext())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setup1()
    }

    private fun setup1() {
        val future = ProcessCameraProvider.getInstance(requireContext())
        future.addListener(Runnable { setup(future) }, mainExecutor)
    }

    private fun setup(future: ListenableFuture<ProcessCameraProvider>) {
        val cameraProvider:ProcessCameraProvider = future.get()

        val screenAspectRatio = AspectRatio.RATIO_4_3
        val rotation = previewView.display.rotation

        // Bind the CameraProvider to the LifeCycleOwner
        val cameraSelector = CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build()

        // Preview
        val preview = Preview.Builder()
            // We request aspect ratio but no resolution
            .setTargetAspectRatio(screenAspectRatio)
            // Set initial target rotation
            .setTargetRotation(rotation)
            .build()

        // Default PreviewSurfaceProvider
        preview.previewSurfaceProvider = previewView.previewSurfaceProvider


        cameraProvider.unbindAll()
        cameraProvider.bindToLifecycle(this, cameraSelector, preview)
    }
}